<template>
    <div class="flex flex-col h-full">
        <div class="publish-method">
            <div
                class="item"
                :class="channel === 'web' ? 'active' : ''"
                @click="switchChannel('web')"
            >
                <icon name="el-icon-Compass" :size="22" />
                <div class="ml-3">
                    <h3 class="text-base mb-1">免登录窗口</h3>
                    <p class="text-xs text-tx-placeholder">分享链接给其他用户, 无需登录即可直接进行使用</p>
                </div>
            </div>
            <div
                class="item"
                :class="channel === 'api' ? 'active' : ''"
                @click="switchChannel('api')"
            >
                <icon name="el-icon-MessageBox" :size="22" />
                <div class="ml-3">
                    <h3 class="text-base mb-1">API 访问</h3>
                    <p class="text-xs text-tx-placeholder">通过API接入到已有系统中, 或企微、RPA等</p>
                </div>
            </div>
        </div>
        <div class="publish-records">
            <div class="flex justify-between">
                <h2 v-if="channel === 'web'" class="text-2xl mb-4">免登录窗口</h2>
                <h2 v-if="channel === 'api'" class="text-2xl mb-4">API 密钥管理</h2>
                <div class="flex">
                    <div v-if="channel === 'api'" class="root-path">
                        <span>API地址:</span>
                        <span @click="handleCopy(config.baseUrl+'/api/v1/chat/completions')">
                            {{ config.baseUrl }}/api/v1/chat/completions
                        </span>
                    </div>
                    <el-button
                        v-if="robot.power >= permissionEnum.EDIT"
                        class="flex-1"
                        @click="handlePopup"
                    >
                        <span class="mb-1 text-3xl">+</span>
                        <span class="ml-2">新建</span>
                    </el-button>
                </div>
            </div>

            <el-table :data="pager.lists" size="large" row-class-name="h-[50px]">
                <el-table-column label="名称" prop="name" min-width="100" />
                <el-table-column v-if="channel === 'api'" label="ApiKey" prop="api_key" min-width="100" />
                <el-table-column label="已用额度" prop="max_price" min-width="100">
                    <template #default="scope: { row: RobotPublishListResponse }">
                        {{ scope.row?.use_points }}/{{ scope.row?.max_points ? scope.row?.max_points : '无限制' }}
                    </template>
                </el-table-column>
                <el-table-column label="IP限流 (分钟)" prop="rpm_limit" min-width="110">
                    <template #default="scope: { row: RobotPublishListResponse }">
                        {{ scope.row?.rpm_limit ? scope.row?.rpm_limit : '无限制'  }}
                    </template>
                </el-table-column>
                <el-table-column label="失效时间" prop="expire_time" min-width="100" />
                <el-table-column label="创建时间" prop="create_time" min-width="100" />
                <el-table-column label="最后使用时间" prop="last_time" min-width="100" />
                <el-table-column fixed="right" label="操作" min-width="90">
                    <template #default="scope: { row: RobotPublishListResponse }">
                        <el-dropdown>
                            <icon name="el-icon-MoreFilled" color="#999" />
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item v-if="scope.row.scene === 'web'">
                                        <div
                                            class="flex items-center py-[2px]"
                                            @click="handleUse(scope.row.api_key)"
                                        >
                                            <icon name="el-icon-ChatDotRound" />
                                            <span class="ml-1">开始使用</span>
                                        </div>
                                    </el-dropdown-item>
                                    <el-dropdown-item v-if="channel === 'api'">
                                        <div
                                            class="flex items-center py-[2px]"
                                            @click="handleCopy(scope.row.api_key)"
                                        >
                                            <icon name="el-icon-CopyDocument" />
                                            <span class="ml-1">复制密钥</span>
                                        </div>
                                    </el-dropdown-item>
                                    <el-dropdown-item>
                                        <div
                                            class="flex items-center py-[2px]"
                                            @click="handlePopup(scope.row)"
                                        >
                                            <icon name="el-icon-Edit" />
                                            <span class="ml-1">编辑</span>
                                        </div>
                                    </el-dropdown-item>
                                    <el-dropdown-item divided>
                                        <div
                                            class="flex items-center py-[2px]"
                                            @click="handleDelete(scope.row.id)"
                                        >
                                            <icon name="el-icon-Delete" />
                                            <span class="ml-1">删除</span>
                                        </div>
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </template>

                </el-table-column>
            </el-table>
        </div>

        <ClientOnly>
            <popup
                :show="popupShow"
                width="400px"
                :title="formData.id ? '更新Key' : '创建Key'"
                :async-close="true"
                @close="popupShow = false"
                @confirm="handleUpdate"
            >
                <div class="p-4 pr-6 pb-0">
                    <el-form label-width="90px" label-position="right">
                        <el-form-item label="名称">
                            <el-input
                                v-model="formData.name"
                                placeholder="分享的名称"
                                autocomplete="off"
                            />
                        </el-form-item>
                        <el-form-item v-if="channel === 'web'" label="访问密码">
                            <el-input
                                v-model="formData.api_secret"
                                placeholder="留空则无需密码"
                                autocomplete="off"
                            />
                        </el-form-item>
                        <el-form-item label="过期时间" >
                            <el-date-picker
                                v-model="formData.expire_time"
                                style="width: 100%"
                                type="datetime"
                                placeholder="年/月/日 --:--"
                            />
                        </el-form-item>
                        <el-form-item label="上限额度">
                            <el-input
                                v-model="formData.max_points"
                                type="number"
                                min="0"
                                placeholder="0/留空则无限制"
                                autocomplete="off"
                            />
                        </el-form-item>
                        <el-form-item label="QPM">
                            <el-input
                                v-model="formData.rpm_limit"
                                type="number"
                                min="0"
                                placeholder="0/留空则无限制"
                                autocomplete="off"
                            />
                        </el-form-item>
                    </el-form>
                </div>
            </popup>
        </ClientOnly>
    </div>
</template>

<script setup lang="ts">
import { useClipboard } from '@vueuse/core'
import { permissionEnum } from '~/enums/app'
import robotPublishApi from '~/api/agent/robot/publish'
import config from '~/config'

const props = withDefaults(
    defineProps<{
        robot: RobotSmarterDetailResponse
    }>(),
    {}
)

const { copy } = useClipboard()

const channel = ref('web')
const popupShow = ref(false)
const formData = reactive<any>({
    id: 0,
    bot: props.robot.code,
    scene: channel.value,
    name: '',
    api_secret: '',
    rpm_limit: '',
    max_points: '',
    expire_time: ''
})

// 查询参数
const queryParams = reactive({
    scene: channel.value,
    bot: props.robot.code
})

// 分页查询
const { pager, queryLists, resetPaging } = usePaging({
    fetchFun: robotPublishApi.lists,
    params: queryParams
})

/**
 * 切换渠道
 *
 * @param {string} type
 * @author zero
 */
const switchChannel = async (type: string) => {
    channel.value = type
    formData.scene = type
    queryParams.scene = type
    await resetPaging()
}

/**
 * 编辑弹窗
 *
 * @param {any} row
 * @author zero
 */
const handlePopup = async (row: any) => {
    if (row.id) {
        formData.id = row.id
        formData.name = row.name
        formData.api_secret = row.api_secret
        formData.max_points = row.max_points
        formData.rpm_limit = row.rpm_limit
        formData.expire_time = row.expire_time
    } else {
        formData.id = 0
        formData.name = ''
        formData.api_secret = ''
        formData.max_points = ''
        formData.rpm_limit = ''
        formData.expire_time = ''
    }
    popupShow.value = true
}

/**
 * 处理更新
 *
 * @author zero
 */
const handleUpdate = async () => {
    const params = Object.assign({}, formData)

    params.max_points = params.max_points ? params.max_points : 0
    params.rpm_limit = params.rpm_limit ? params.rpm_limit : 0
    if (formData.expire_time) {
        const date = new Date(formData.expire_time)
        params.expire_time = date.getTime() / 1000
    } else {
        params.expire_time = 0
    }

    if (!formData.id) {
        await robotPublishApi.add(params)
        feedback.msgSuccess('创建成功')
    } else {
        await robotPublishApi.edit(params)
        feedback.msgSuccess('编辑成功')
    }

    popupShow.value = false
    await queryLists()
}

/**
 * 处理删除
 *
 * @param {number} id
 * @author zero
 */
const handleDelete = (id: number) => {
    feedback.confirm('确定要删除秘钥吗?').then(async () => {
        await robotPublishApi.delete(id)
        feedback.msgSuccess('删除成功')
        await resetPaging()
    }).catch(() => {})
}

/**
 * 处理复制
 *
 * @param {string} content
 * @author zero
 */
const handleCopy = async (content: string) => {
    await copy(content)
    feedback.msgSuccess('复制成功')
}

/**
 * 处理使用
 *
 * @param apiKey
 * @author zero
 */
const handleUse = async (apiKey: string) => {
    const url = '/chats/publish/' + apiKey
    window.open(url, '_blank')
}

onMounted(async () => {
    await queryLists()
})
</script>

<style scoped lang="scss">
.publish-method {
    display: flex;
    column-gap: 20px;
    padding: 24px 32px;
    margin-bottom: 10px;
    background-color: var(--el-bg-color);
    border-radius: 8px;
    .item {
        display: flex;
        align-items: center;
        padding: 12px 16px;
        color: var(--el-text-color-regular);
        cursor: pointer;
        user-select: none;
        background-color: var(--el-color-light);
        border: 1.5px solid var(--el-border-color-light);
        border-radius: 12px;
        &.active,
        &:hover {
            border-color: var(--el-color-primary);
        }
    }
}

.publish-records {
    flex: 1;
    padding: 24px;
    background-color: var(--el-bg-color);
    border-radius: 8px;
}

.root-path {
    display: flex;
    align-items: center;
    height: 33px;
    padding: 0 10px;
    margin-right: 20px;
    color: var(--el-text-color-secondary);
    background-color: var(--el-bg-color-light);
    border-radius: 4px;
    span { display: inline-block;  }
    span:first-child {
        padding: 2px 4px;
        margin-right: 8px;
        font-size: 12px;
        color: var(--el-text-color-secondary);
        background-color: var(--el-bg-color);
        border-radius: 3px;
    }
}
</style>
